#include "transferfile.h"

//********************************************************************************
//接收指令函数
//********************************************************************************
task_t *recvCmd(int peerfd)
{
	task_t *ptask = (task_t *)calloc(1, sizeof(task_t)); // calloc同时也进行了初始化操作

	ptask->peerfd = peerfd;

	//先接收指令类型;
	recvCircle(peerfd, (char *)&ptask->type, 4);

	printf("指令类型为：%d\n", ptask->type);

	//再接收指令参数
	int cmdlength = 0;
	memset(&ptask->data,0,1024);
	recvCircle(peerfd, (char *)&cmdlength, 4);
	recvCircle(peerfd, ptask->data, cmdlength);
	printf(">>>>datasize:%ld\n",strlen(ptask->data));
	return ptask;
}

//********************************************************************************
//接收信息函数，接收length长度信息到buff
//********************************************************************************
int recvCircle(int fd, char *buff, int length)
{
	char *pbuf = buff;
	int left = length;
	int ret = 0;
	while (left > 0)
	{
		ret = recv(fd, pbuf, left, 0);
		if (0 == ret)
		{
			close(fd);
			break;
		}
		else if (ret == -1 && errno == EINTR)
		{
			continue;
		}
		else if (ret == -1)
		{
			perror("recv");
			break;
		}
		else
		{ // > 0
			pbuf += ret;
			left -= ret;
		}
	}
	return length - left;
}